<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="organizationRegister"
    @ok="confirmSubmit"
    @close="drawerReset"
    width="1000"
    showFooter
    isAbsolute
    getContainer=".page-wrapper"
  >
    <div class="box-drawer" v-loading="infoLoading">
      <div class="drawer-box">
        <div class="box-title">租户基本信息</div>
        <div class="box-form" ref="eleRef" v-show="drawerInfo.type === operateActionType.ADD">
          <BasicForm @register="userForm">
            <template #info="{ model, field }">
              <div class="form-info" v-if="drawerInfo.type !== operateActionType.VIEW">
                <info-circle-outlined :style="{ fontSize: '14px', marginRight: '4px' }" />
                管理员手机号码/管理员邮箱将作为用户账号，请选择进行填写，新建成功后，账号密码将发送至该管理员手机号码/管理员邮箱
              </div>
            </template>
          </BasicForm>
        </div>
        <div class="box-form box-flex" v-if="drawerInfo.type !== operateActionType.ADD">
          <div class="form-item" v-if="drawerInfo.type === operateActionType.VIEW">
            <div class="item-label">租户状态</div>
            <div class="item-value" v-if="formAuthState.record.orgStatus == 0">启用</div>
            <div class="item-value" v-else-if="formAuthState.record.orgStatus == 1">停用</div>
          </div>
          <div class="form-item" v-else-if="drawerInfo.type === operateActionType.EDIT">
            <div class="item-label">租户状态</div>
            <div class="item-value">
              <a-switch
                v-model:checked="formAuthState.orgStatus"
                checked-children="启用"
                un-checked-children="停用"
                @change="switchChange"
              />
            </div>
          </div>
          <div class="form-item">
            <div class="item-label">注册来源</div>
            <div class="item-value">{{ formAuthState.record.regChannelValue || '-' }}</div>
          </div>
          <div class="form-item">
            <div class="item-label">租户名称</div>
            <div class="item-value">{{ formAuthState.record.orgName || '-' }}</div>
          </div>
          <div class="form-item">
            <div class="item-label">主机构税号</div>
            <div class="item-value">{{ formAuthState.record.taxesNumber || '-' }}</div>
          </div>
          <div class="form-item">
            <div class="item-label">纳税人类型</div>
            <div class="item-value" v-if="formAuthState.record.taxesType == 0">小规模纳税人</div>
            <div class="item-value" v-else-if="formAuthState.record.taxesType == 1">一般纳税人</div>
          </div>
          <div class="form-item">
            <div class="item-label">管理员账号</div>
            <div class="item-value">{{ formAuthState.record.adminAccount || '-' }}</div>
          </div>
          <div class="form-item">
            <div class="item-label">创建人</div>
            <div class="item-value">{{ formAuthState.record.createName || '-' }}</div>
          </div>
          <div class="form-item">
            <div class="item-label">创建时间</div>
            <div class="item-value">{{ formAuthState.record.createDate || '-' }}</div>
          </div>
          <div class="form-item form-block" v-if="currentUserType == 1">
            <div class="item-label" style="line-height: 32px" v-if="drawerInfo.type === operateActionType.EDIT">
              渠道名称
            </div>
            <div class="item-label" v-else>渠道名称</div>
            <div class="item-value" style="width: 100%">
              <a-tree-select
                style="width: 100%"
                v-if="drawerInfo.type === operateActionType.EDIT"
                v-model:value="channelObj.channelCode"
                placeholder="请选择渠道名称"
                :tree-data="channelObj.channelTreeData"
                :field-names="{
                  label: 'channelName',
                  value: 'channelCode',
                  children: 'children'
                }"
                treeNodeFilterProp="channelName"
                showSearch
                allowClear
              ></a-tree-select>
              <div v-else>{{ formAuthState.record.channelName || '-' }}</div>
            </div>
          </div>
          <div class="form-item form-block">
            <div class="item-label">备注信息</div>
            <div class="item-value" style="width: 100%">
              <a-textarea
                allowClear
                :maxLength="100"
                v-if="drawerInfo.type === operateActionType.EDIT"
                :autoSize="{ minRows: 3, maxRows: 3 }"
                placeholder="请输入备注信息，中文100字以内"
                v-model:value.trim="formAuthState.record.orgRemark"
              >
              </a-textarea>
              <div v-else>{{ formAuthState.record.orgRemark || '-' }}</div>
            </div>
          </div>
        </div>
      </div>
      <div class="drawer-box">
        <div class="box-title">租户授权设置</div>
        <div class="box-form" v-if="drawerInfo.type !== operateActionType.VIEW">
          <a-form :model="formAuthState" :colon="false" :label-col="{ style: { width: '150px' } }">
            <a-form-item>
              <template #label>
                <div class="flex-label">
                  <div class="label-value">新增企业用户</div>
                  <a-tooltip>
                    <template #title>开启后， 该租户下可无限新增用户</template>
                    <div class="label-icon">
                      <info-circle-outlined :style="{ fontSize: '14px', marginLeft: '4px' }" />
                    </div>
                  </a-tooltip>
                </div>
              </template>
              <a-switch
                v-model:checked="formAuthState.tenantUserAuthFlag"
                checked-children="是"
                un-checked-children="否"
              />
            </a-form-item>
            <a-form-item>
              <template #label>
                <div class="flex-label">
                  <div class="label-value">新增下级企业</div>
                  <a-tooltip>
                    <template #title>开启后， 该租户下可无限新增下级企业</template>
                    <div class="label-icon">
                      <info-circle-outlined :style="{ fontSize: '14px', marginLeft: '4px' }" />
                    </div>
                  </a-tooltip>
                </div>
              </template>
              <a-switch
                v-model:checked="formAuthState.companyAuthFlag"
                checked-children="是"
                un-checked-children="否"
              />
              <a-input-number
                style="width: 200px"
                v-if="!formAuthState.companyAuthFlag"
                :precision="0"
                placeholder="请输入下级企业数量"
                v-model:value="formAuthState.maxOrgCount"
                :min="1"
                :max="2147483647"
              />
              <span class="text-info" v-if="!formAuthState.companyAuthFlag">（说明：请填写可增加的下级企业数量）</span>
            </a-form-item>
            <a-form-item>
              <template #label>
                <div class="flex-label">
                  <div class="label-value">有效截止时间</div>
                  <a-tooltip>
                    <template #title>有效时间到期后租户状态将自动变为停用状态，若启用需重新设置有效时间</template>
                    <div class="label-icon">
                      <info-circle-outlined :style="{ fontSize: '14px', marginLeft: '4px' }" />
                    </div>
                  </a-tooltip>
                </div>
              </template>
              <a-radio-group name="radioGroup" v-model:value="formAuthState.timeType">
                <a-radio value="1">永久</a-radio>
                <a-radio value="2">
                  自定义时间
                  <a-date-picker
                    v-model:value="formAuthState.endDate"
                    :disabledDate="disabledDate"
                    v-if="formAuthState.timeType == '2'"
                    :style="{ width: '200px', marginLeft: '8px' }"
                    format="YYYY-MM-DD"
                    valueFormat="YYYY-MM-DD"
                    placeholder="请选择时间"
                  ></a-date-picker>
                </a-radio>
              </a-radio-group>
            </a-form-item>
            <a-form-item>
              <template #label>
                <div class="flex-label">
                  <div class="label-value">是否隐藏财税BPai入口</div>
                  <a-tooltip>
                    <template #title>开启后， 该租户将不显示财税BPai入口</template>
                    <div class="label-icon">
                      <info-circle-outlined :style="{ fontSize: '14px', marginLeft: '4px' }" />
                    </div>
                  </a-tooltip>
                </div>
              </template>
              <a-switch v-model:checked="formAuthState.ycHiddenFlag" checked-children="是" un-checked-children="否" />
            </a-form-item>
          </a-form>
        </div>
        <div class="box-form box-flex" v-else>
          <div class="form-item form-block">
            <div class="item-label">新增企业用户</div>
            <div class="item-value" v-if="formAuthState.record.tenantUserAuthFlag == 0">是</div>
            <div class="item-value" v-else-if="formAuthState.record.tenantUserAuthFlag == 1">否</div>
          </div>
          <div class="form-item form-block">
            <div class="item-label">新增下级企业</div>
            <div class="item-value" v-if="formAuthState.companyAuthFlag">是</div>
            <template v-else>
              <div class="item-value">否</div>
              <div class="item-value sonOrgCount">最大新增企业数量：{{ formAuthState.maxOrgCount }}个</div>
            </template>
          </div>
          <div class="form-item form-block">
            <div class="item-label">有效截止时间</div>
            <div class="item-value">
              {{
                formAuthState.record.endTimeRemainingDays || formAuthState.record.endTimeRemainingDays === 0
                  ? `${formAuthState.record.endTimeRemainingDays}天`
                  : '永久'
              }}
            </div>
          </div>
          <div class="form-item form-block">
            <div class="item-label">隐藏财税BPai入口</div>
            <div class="item-value" v-if="formAuthState.record.ycHiddenFlag == 1">否</div>
            <div class="item-value" v-else-if="formAuthState.record.ycHiddenFlag == 2">是</div>
          </div>
        </div>
      </div>
      <div class="drawer-box" v-if="drawerInfo.type !== operateActionType.ADD">
        <div class="box-title">购买记录</div>
        <div class="box-form box-auth">
          <a-table :columns="authColumns" :dataSource="drawerInfo.authList" :pagination="false">
            <template #bodyCell="{ column, record }">
              <template v-if="column.dataIndex === 'time'">
                <span v-if="record.authTimeStart && record.authTimeEnd">
                  {{ record.authTimeStart }} ~ {{ record.authTimeEnd }}
                </span>
              </template>
              <template v-else-if="column.dataIndex === 'packageName'">
                <EllipsisTooltip :title="record.packageName" :width="200">
                  {{ record.packageName }}
                </EllipsisTooltip>
              </template>
            </template>
          </a-table>
          <div class="auth-page">
            <a-pagination
              v-model:current="pageObj.pageNo"
              v-model:page-size="pageObj.pageSize"
              :total="pageObj.total"
              size="small"
              show-size-changer
              @change="onChange"
              hideOnSinglePage
              :show-total="(total:number) => `共 ${total} 条数据`"
            />
          </div>
        </div>
      </div>
    </div>
    <template #insertFooter v-if="drawerInfo.type === operateActionType.EDIT">
      <a-button type="primary" @click="resetPwd"> 重置密码 </a-button>
    </template>
  </BasicDrawer>
</template>

<script lang="ts" setup>
import { reactive, ref, computed } from 'vue'
import { BasicDrawer, useDrawerInner } from '@/components/Drawer'
import { BasicForm, FormSchema, useForm } from '@/components/Form/index'
import { getNewTenantFormConfig } from '../dataSource'
import { getUpdateSchemaArr } from '@/utils/formSchema'
import { numTransString, getFormatAuthList, scrollToFirstError, transformToTree } from '@/utils'
import { InfoCircleOutlined } from '@ant-design/icons-vue'
import { operateActionType } from '@/types/enum'
import { userStore } from '@/store/modules/user'
import dayjs, { Dayjs } from 'dayjs'
type RangeValue = [Dayjs, Dayjs]
import { TenantDrawerInfo } from '@/types/tenant'
import EllipsisTooltip from '@/components/EllipsisTooltip/index.vue'
import { message } from 'ant-design-vue'
import api from '@/api'

const {
  enterpriseAdd,
  enterpriseNewUpdate,
  enterpriseDetail,
  getDictItem,
  platformIndustry,
  orderQueryPage,
  userQueryChannelList
} = api
const userModule = userStore()

const emit = defineEmits(['operateSuccess', 'register', 'resetPwd'])
const eleRef = ref<null | HTMLElement>(null)

const currentUserType = computed(() => userModule.userInfo?.userType)

const authColumns = [
  {
    title: '订单编号',
    align: 'center',
    dataIndex: 'orderNo'
  },
  {
    title: '购买套餐',
    align: 'center',
    width: 200,
    dataIndex: 'packageName'
  },
  {
    title: '下单时间',
    align: 'center',
    dataIndex: 'createTime'
  },
  {
    title: '创建人',
    align: 'center',
    dataIndex: 'createBy'
  }
]
// 选择当天之后时间
const disabledDate = (current: Dayjs) => {
  return current && current < dayjs().startOf('day')
}

const infoLoading = ref(false)

const channelObj = reactive<any>({
  channelCode: null,
  channelTreeData: []
})

const drawerInfo = reactive<TenantDrawerInfo>({
  type: '',
  tenantId: '',
  authList: []
})

const formAuthState = reactive<any>({
  tenantUserAuthFlag: true,
  ycHiddenFlag: false,
  companyAuthFlag: true,
  maxOrgCount: null,
  endDate: '', // 时间
  timeType: '1', // 1永久 2选择时间
  orgStatus: false,
  record: {}
})

const pageObj = reactive({
  total: 0,
  pageNo: 1,
  pageSize: 10
})

const tenantFormConfig = getNewTenantFormConfig()
const [userForm, { setFieldsValue, getFieldsValue, validate, resetFields, updateSchema, setProps }] =
  useForm(tenantFormConfig)

const [organizationRegister, { closeDrawer, changeOkLoading }] = useDrawerInner(async (data) => {
  drawerInfo.type = data.type
  updateSchema(getUpdateSchemaArr(tenantFormConfig.schemas, data.type))

  if (data.type !== operateActionType.ADD) {
    drawerInfo.tenantId = data.tenantId
    try {
      infoLoading.value = true
      let res = await enterpriseDetail({ orgTenantId: data.tenantId })
      if (currentUserType.value == 1 && data.type === operateActionType.EDIT) {
        const channelRes = await userQueryChannelList()
        channelObj.channelTreeData = transformToTree(channelRes.result)
      }
      infoLoading.value = false
      if (res.result) {
        let result = res.result
        formAuthState.record = { ...result, ...data.record } || {}
        formAuthState.orgStatus = result.orgStatus == 0
        formAuthState.tenantUserAuthFlag = result.tenantUserAuthFlag == 0
        formAuthState.ycHiddenFlag = result.ycHiddenFlag == 2
        channelObj.channelCode = result.channelCode || null
        console.log('maxOrgCount====>', result.maxOrgCount)
        // 子企业数有值时开关关闭，为null时开关打开
        if (typeof result.maxOrgCount === 'number') {
          formAuthState.companyAuthFlag = false
          formAuthState.maxOrgCount = result.maxOrgCount
        } else {
          formAuthState.companyAuthFlag = true
        }
        if (data.record.endTime) {
          formAuthState.timeType = '2'
          formAuthState.endDate = data.record.endTime
        }
      }
      // 授权记录
      if (data.type !== operateActionType.ADD) {
        pageObj.pageNo = 1
        getAuthList()
      }
    } catch (error) {
      infoLoading.value = false
    }
  }
})

const getAuthList = async () => {
  let res = await orderQueryPage({
    page: {
      pageNo: pageObj.pageNo,
      pageSize: pageObj.pageSize
    },
    buyerTenantId: drawerInfo.tenantId
  })
  let result = res.result || {}

  drawerInfo.authList = result.records || []
  pageObj.total = result.total || 0
}
// 分页调整
const onChange = (pageNo: number, pageSize: number) => {
  pageObj.pageNo = pageNo
  if (pageSize != pageObj.pageSize) {
    pageObj.pageNo = 1
  }
  pageObj.pageSize = pageSize
  getAuthList()
}

const drawerReset = () => {
  changeOkLoading(false)
  infoLoading.value = false
  formAuthState.tenantUserAuthFlag = true
  formAuthState.ycHiddenFlag = false
  formAuthState.timeType = '1'
  formAuthState.endDate = ''
  channelObj.channelCode = null
  drawerInfo.authList = []
  formAuthState.companyAuthFlag = true
  formAuthState.maxOrgCount = null
  resetFields()
}

const resetPwd = () => {
  emit('resetPwd')
}

const switchChange = (checked: boolean) => {
  if (checked) {
    formAuthState.timeType = '1'
  }
}
// 提交数据
const confirmSubmit = async () => {
  try {
    let formValue = getFieldsValue()
    if (drawerInfo.type === operateActionType.ADD) {
      await validate()
      if (!formValue.contactEmail && !formValue.contactPhone) {
        return message.error('管理员手机号码和管理员邮箱必须填写一项')
      }
    }

    if (formAuthState.timeType == '2' && !formAuthState.endDate) {
      return message.error('请选择有效截止时间')
    }
    if (!formAuthState.companyAuthFlag && formAuthState.maxOrgCount === null) {
      return message.error('请输入下级企业数量')
    }
    changeOkLoading(true)
    if (drawerInfo.type === operateActionType.ADD) {
      let reqData: any = {
        ...formValue,
        tenantUserAuthFlag: formAuthState.tenantUserAuthFlag ? 0 : 1,
        ycHiddenFlag: formAuthState.ycHiddenFlag ? 2 : 1,
        endDate: formAuthState.timeType == '2' ? formAuthState.endDate : null,
        regChannel: 0,
        maxOrgCount: formAuthState.companyAuthFlag ? null : formAuthState.maxOrgCount
      }

      await enterpriseAdd(reqData)
    } else if (drawerInfo.type === operateActionType.EDIT) {
      let reqData: any = {
        tenantUserAuthFlag: formAuthState.tenantUserAuthFlag ? 0 : 1,
        ycHiddenFlag: formAuthState.ycHiddenFlag ? 2 : 1,
        orgTenantId: drawerInfo.tenantId,
        orgStatus: formAuthState.orgStatus ? 0 : 1,
        endDate: formAuthState.timeType == '2' ? formAuthState.endDate : null,
        orgRemark: formAuthState.record.orgRemark,
        channelCode: channelObj.channelCode || '',
        maxOrgCount: formAuthState.companyAuthFlag ? null : formAuthState.maxOrgCount
      }

      await enterpriseNewUpdate(reqData)
    }
    message.success(drawerInfo.type === operateActionType.ADD ? '租户新增成功' : '租户编辑成功')
    closeDrawer()
    drawerReset()
    emit('operateSuccess')
  } catch (error) {
    changeOkLoading(false)
    if (eleRef.value) {
      scrollToFirstError(eleRef.value)
    }
  }
}
</script>

<style lang="less" scoped>
.box-drawer {
  padding: 8px 0;
  position: relative;
  .drawer-box {
    margin-bottom: 24px;
    &:last-of-type {
      margin-bottom: 0;
    }
    .box-title {
      padding-left: 12px;
      padding-bottom: 8px;
      margin-bottom: 16px;
      font-size: 16px;
      font-weight: 600;
      color: @text-color;
      line-height: 22px;
      position: relative;
      border-bottom: 1px solid #e8e8e8;
      &::before {
        content: '';
        width: 4px;
        height: 16px;
        background: @primary-color;
        border-radius: 2px;
        position: absolute;
        left: 0;
        top: 2px;
      }
    }
    .box-form {
      padding: 24px 190px 4px 24px;
      position: relative;
      &.box-auth {
        width: 100%;
        padding-right: 24px;
        padding-top: 8px;
        .auth-page {
          margin-top: 20px;
          display: flex;
          justify-content: flex-end;
        }
      }
      &.box-flex {
        display: flex;
        align-items: center;
        flex-wrap: wrap;
        .form-item {
          width: 360px;
          padding-right: 20px;
          margin-bottom: 24px;
          font-size: 12px;
          display: flex;
          &.form-block {
            width: 100%;
          }
          .item-label {
            width: 115px;
            text-align: right;
            color: #192236;
            margin-right: 4px;
            font-weight: 600;
            flex-shrink: 0;
          }
          .item-value {
            margin-left: 6px;
            color: #192235;
          }
          .sonOrgCount {
            margin-left: 10px;
          }
        }
      }
      .form-info {
        padding-left: 28px;
        font-size: 12px;
        color: #c0c0c0;
        display: flex;
        align-items: center;
      }
      .flex-label {
        display: flex;
        align-items: center;
        .label-icon {
          color: #c0c0c0;
          display: flex;
          align-items: center;
          cursor: pointer;
          &:hover {
            color: @primary-color;
          }
        }
      }
      :deep(.item-time) {
        margin-bottom: 0;
        .ant-form-item-control-input-content {
          display: flex;
          flex-direction: column;
          .time-show {
            width: 280px;
            margin-bottom: 12px;
          }
        }
      }
      :deep(.ant-input-number) {
        margin-left: 10px;
      }
    }
  }
  :deep(.ant-form-item-label) {
    font-weight: 600;
    & > label {
      font-size: 12px;
    }
  }
}
.text-info {
  color: #c0c0c0;
  font-size: 12px;
  margin-left: 8px;
}
</style>
